import express from 'express';
import { createServer } from 'node:http';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { Server } from 'socket.io';

const app = express();
const server = createServer(app);
const io = new Server(server);

// 创建一个map
const users = new Map();

// 表示当前文件所在的目录
const __dirname = dirname(fileURLToPath(import.meta.url));

app.get('/', (req, res) => {
    res.sendFile(join(__dirname, 'index.html'));
});

io.on('connection', (socket) => {
    console.log('a user connected, socketId: ', socket.id);
    users.set(socket.id, socket);

    socket.on('disconnect', () => {
        console.log('user disconnected, socketId: ', socket.id);
        users.delete(socket.id);
    });

    socket.on('chat message', (msg) => {
        console.log('发送者: ' + socket.id +  ', message: ' + msg);
        io.emit('chat message', msg);
        // socket.broadcast.emit('chat message', msg);
    });
});

server.listen(3000, () => {
    console.log('server running at http://localhost:3000');
});